#include "webapplication.h"
#include "qwebframe.h"

void WebApplication::setStyleSheet(QString url) {
	QByteArray styleSheet = this->networkManager->get(url);
	styleSheet = styleSheet.toBase64();
	QUrl styleSheetUrl = QUrl("data:text/css;charset=utf-8;base64," + styleSheet);
	QWebSettings* settings = this->webPage->settings()->globalSettings();
	settings->setUserStyleSheetUrl(styleSheetUrl);
}

void WebApplication::setJavaScript(QString url) {
	this->webPage->mainFrame()->setHtml("", QUrl(url));
	QByteArray response = this->networkManager->get(url);
	this->webPage->mainFrame()->evaluateJavaScript("(function() {"
		"var application = window[''];"
		"delete window[''];"
		+ response +
	"})();");
}

/* public methods */

WebApplication::WebApplication(QApplication* application): WebHost(application) {
	this->exitCode = 0;
	this->application = application;
	this->application->setQuitOnLastWindowClosed(false);

	this->networkManager = new NetworkManager();
	this->webPage->setNetworkAccessManager(this->networkManager);
	this->resourceManager = new ResourceManager(application);
	QObject::connect(this->networkManager, SIGNAL(
		createRequest(QUrl)
	), this->resourceManager, SLOT(createRequest(QUrl)));
	QObject::connect(this->webPage->mainFrame(), SIGNAL(
		javaScriptWindowObjectCleared()
	), this, SLOT(javaScriptApplicationObjectCleared()));
	this->setStyleSheet("res:///main.css");
	this->setJavaScript("res:///main.js");
}

WebApplication::~WebApplication() {
	delete this->resourceManager;
	delete this->networkManager;
}

int WebApplication::getExitCode() {
	return this->exitCode;
}

void WebApplication::javaScriptApplicationObjectCleared() {
	this->webPage->mainFrame()->addToJavaScriptWindowObject("", this);
}

/* exposed declarations */

void WebApplication::run() {
	this->application->exec();
}

void WebApplication::terminate(int exitCode) {
	this->exitCode = exitCode;
	this->application->quit();
}
